/*
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */
package com.foridev.gec.dao;

import com.foridev.gec.model.Acte;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.ejb.HibernateEntityManager;
import org.hibernate.ejb.HibernatePersistence;

public class ActeDao {

    private EntityManagerFactory emf;
    private EntityManager em;

    public ActeDao() {
        emf = new HibernatePersistence().createEntityManagerFactory("persistenceActeUnit", new HashMap());
        em = emf.createEntityManager();
    }

    public void close() {
        em.close();
        emf.close();
        em = null;
        emf = null;
    }

    public Acte getById(Integer id) {
        return em.find(Acte.class, id);
    }

    public void persist(Acte acte) {
        em.getTransaction().begin();
        em.merge(acte);
        em.getTransaction().commit();
    }

    public List<Acte> getAll(int order, String col) {
        if (order == 0) {
            return em.createQuery("select a from Acte a order by ".concat(col).concat(" asc")).getResultList();
        } else {
            return em.createQuery("select a from Acte a order by ".concat(col).concat(" desc")).getResultList();
        }
    }

    public Integer getTotalCount() {
        HibernateEntityManager hem = (HibernateEntityManager) em;
        return (Integer) hem.getSession().createCriteria(Acte.class).setProjection(Projections.rowCount()).uniqueResult();
    }

    public List<Acte> getAll(int order, String col, int pos, int total) {
        HibernateEntityManager hem = (HibernateEntityManager) em;
        System.out.println("****** getAll(int order,String col,int pos, int total) *****  " + pos);
        if (order == 0) {
            return hem.getSession().createCriteria(Acte.class).addOrder(Order.asc(col))
                    .setFirstResult(pos).setMaxResults(total).list();
//            System.out.println("select a from Acte a ".concat("limit 1 offset ").concat(String.valueOf(pos)).concat(" order by ").concat(col));
//            return em.createQuery("select a from Acte a order by ".concat(col).concat(" asc LIMIT 1 OFFSET ").concat(String.valueOf(pos))).getResultList();
        } else {
            return hem.getSession().createCriteria(Acte.class).addOrder(Order.desc(col))
                    .setFirstResult(pos).setMaxResults(total).list();
//            return em.createQuery("select a from Acte a order by ".concat(col).concat(" desc LIMIT 1 OFFSET ").concat(String.valueOf(pos))).getResultList();
        }
    }

    public List<Acte> getActesWithFilters() {
        return em.createQuery("select a from Acte a").getResultList();
    }
}